package com.taomus.mytools.crypto;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
 * DES 8的倍数 加密解密均使用了base64
 * @author mrc
 */
public class CrypotDES {
	private static byte[] iv = {1,2,3,4,5,6,7,8};
    private static IvParameterSpec zeroIv = new IvParameterSpec(iv);
    
    public static void setIvParameterSpec(byte[] inIv){
    	zeroIv = new IvParameterSpec(inIv);
    }
	/**
	 * 加密
	 * @param pwd String 密码
	 * @param value String 
	 * @return String
	 */
	public static String encrypt(String pwd,String value){
		try {
			DESKeySpec  deskey = new DESKeySpec(pwd.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(deskey);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE,securekey,zeroIv);
			byte[] desBytes = cipher.doFinal(value.getBytes());
			return new String(CryptoHelper.base64Encode(desBytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 解密
	 * @param pwd
	 * @param value 
	 * @return
	 */
	public static String decrypt(String pwd,String value){
		try {
			DESKeySpec  deskey = new DESKeySpec(pwd.getBytes());
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(deskey);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE,securekey,zeroIv);
			byte[] base64Bytes = CryptoHelper.base64Decode(value.getBytes());
			return new String(cipher.doFinal(base64Bytes));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
